package com.seocoo.worker.home;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.seocoo.worker.R;
import com.seocoo.worker.base.PermissionUtil;
import com.seocoo.worker.base.entity.EVersion;
import com.seocoo.worker.base.version.APKLoadService;

public class VersionDialog extends DialogFragment implements View.OnClickListener {
    public static void showDialogUI(FragmentActivity activity, EVersion eVersion) {
        VersionDialog dialog = new VersionDialog();
        dialog.showDialog(activity, eVersion);
    }

    TextView tv_ok;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.version_dialog, container, false);
        View iv_close = view.findViewById(R.id.iv_close);
        iv_close.setOnClickListener(this);

        tv_ok = view.findViewById(R.id.tv_ok);
        tv_ok. setOnClickListener(this);

        TextView tv_content = view.findViewById(R.id.tv_content);
        tv_content.setText(eVersion.description);
        if (eVersion != null && eVersion.forcedUpdate == 1) {
            //强制更新
            getDialog().setCancelable(false);
            getDialog().setCanceledOnTouchOutside(false);
            iv_close.setVisibility(View.GONE);
        }
        LocalBroadcastManager.getInstance(this.getContext()).registerReceiver(receiver, new IntentFilter(APKLoadService.ACTION));
        return view;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        super.onActivityCreated(savedInstanceState);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(0x00000000));
        getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        if (eVersion != null && eVersion.forcedUpdate == 1) {
            //强制更新
            getDialog().setCancelable(false);
            getDialog().setCanceledOnTouchOutside(false);
        }
    }

    EVersion eVersion;

    private void showDialog(FragmentActivity activity, EVersion eVersion) {

        try {
            this.eVersion = eVersion;
            if (activity == null) {
                return;
            }
            if (isAdded()) {
                return;
            }
            super.show(activity.getSupportFragmentManager(), this.getClass().getName());

        } catch (Exception e) {
        }
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_close) {
            this.dismiss();
        } else if (v.getId() == R.id.tv_ok) {
            tv_ok.setEnabled(false);
            tv_ok.setText("更新下载...");
            //开始下载
            APKLoadService.startLoadService(getContext(), eVersion);
        }
    }

    @Override
    public void dismiss() {
        LocalBroadcastManager.getInstance(this.getContext()).unregisterReceiver(receiver);
        FragmentActivity activity = this.getActivity();
        if (activity != null && !activity.isFinishing()) {
            this.dismissAllowingStateLoss();
        }
    }
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (!isVisible()) {
                return;
            }
            String type = intent.getStringExtra("type");
            if (TextUtils.equals("ERROR", type)) {
                tv_ok.setEnabled(true);
                tv_ok.setText("立即升级");
                //下载失败，重新打开更新界面重新进行更新
                return;
            }
            long size = intent.getLongExtra("size", 0L);
            if (size > 100) {
                //防止强制更新要求，在apk下载成功之后不安装，启到拦截效果
                return;
            }
            float allSize = intent.getFloatExtra("allSize", 0.0f);
            float loadSize = intent.getFloatExtra("loadSize", 0.0f);

            tv_ok.setText(String.format("更新下载... %.2f M/%.2f M", loadSize, allSize));
        }
    };
}
